<template>
  <div class="dashboard-container gradient-bg">
    <!-- 顶部导航栏 -->
    <header class="header glass">
      <div class="header-left">
        <h1 class="logo">🎮 趣味英语</h1>
      </div>
      <div class="header-center">
        <div class="user-stats">
          <div class="stat-item">
            <span class="icon">⭐</span>
            <span class="value">{{ user?.stars || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="icon">📚</span>
            <span class="value">{{ wordsLearned }}</span>
          </div>
          <div class="stat-item">
            <span class="icon">🔥</span>
            <span class="value">{{ user?.continuous_days || 0 }}</span>
          </div>
        </div>
      </div>
      <div class="header-right">
        <el-dropdown @command="handleCommand">
          <div class="user-info cursor-pointer">
            <span class="avatar">{{ getAvatarEmoji(user?.avatar) }}</span>
            <span class="username">{{ user?.username }}</span>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人资料</el-dropdown-item>
              <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="main-content">
      <!-- 宠物区域 -->
      <section class="pet-section glass rounded-xl float">
        <h2 class="section-title">我的宠物</h2>
        <div v-if="pet" class="pet-display">
          <div class="pet-avatar">
            <span class="pet-icon">{{ getPetIcon(pet.pet_type) }}</span>
            <div class="pet-level">Lv.{{ pet.level }}</div>
          </div>
          <div class="pet-info">
            <h3 class="pet-name">{{ pet.pet_name }}</h3>
            <div class="pet-stats">
              <div class="stat-bar">
                <span class="label">❤️ 健康值</span>
                <el-progress :percentage="pet.health" :color="getHealthColor(pet.health)" />
              </div>
              <div class="stat-bar">
                <span class="label">🍖 饥饿值</span>
                <el-progress :percentage="pet.hunger" color="#ffa500" />
              </div>
              <div class="stat-bar">
                <span class="label">😊 快乐值</span>
                <el-progress :percentage="pet.happiness" color="#ff69b4" />
              </div>
            </div>
            <div class="pet-actions">
              <el-button type="primary" @click="feedPet" :loading="petLoading">
                🍖 喂食
              </el-button>
              <el-button type="success" @click="playWithPet" :loading="petLoading">
                🎮 玩耍
              </el-button>
              <el-button @click="$router.push('/pet')">
                详情
              </el-button>
            </div>
          </div>
        </div>
      </section>

      <!-- 开始学习大按钮 -->
      <section class="quick-start">
        <div class="start-button glass rounded-xl cursor-pointer" @click="$router.push('/learn')">
          <div class="start-icon">📚</div>
          <div class="start-content">
            <h3>开始学习</h3>
            <p>每天10个单词，轻松掌握英语</p>
          </div>
          <el-icon class="arrow"><ArrowRight /></el-icon>
        </div>
      </section>

      <!-- 功能菜单 -->
      <section class="menu-section">
        <div class="menu-grid">
          <div class="menu-item glass rounded-xl cursor-pointer" @click="$router.push('/adventure')">
            <div class="menu-icon">🗺️</div>
            <div class="menu-title">星球冒险</div>
            <div class="menu-desc">探索英语星球</div>
          </div>
          <div class="menu-item glass rounded-xl cursor-pointer" @click="$router.push('/games')">
            <div class="menu-icon">🎮</div>
            <div class="menu-title">趣味游戏</div>
            <div class="menu-desc">寓教于乐</div>
          </div>
          <div class="menu-item glass rounded-xl cursor-pointer" @click="$router.push('/review')">
            <div class="menu-icon">📖</div>
            <div class="menu-title">智能复习</div>
            <div class="menu-desc">每日一练</div>
          </div>
          <div class="menu-item glass rounded-xl cursor-pointer" @click="$router.push('/leaderboard')">
            <div class="menu-icon">🏆</div>
            <div class="menu-title">排行榜</div>
            <div class="menu-desc">与好友竞技</div>
          </div>
          <div class="menu-item glass rounded-xl cursor-pointer" @click="$router.push('/achievements')">
            <div class="menu-icon">🎖️</div>
            <div class="menu-title">成就徽章</div>
            <div class="menu-desc">收集勋章</div>
          </div>
        </div>
      </section>

      <!-- 每日任务 -->
      <section class="tasks-section glass rounded-xl">
        <div class="section-header">
          <h2 class="section-title">每日任务</h2>
          <el-button size="small" @click="loadDashboardData" :loading="loading">
            刷新
          </el-button>
        </div>
        <div v-if="dailyTasks.length === 0 && !loading" class="empty-tasks">
          <p>正在加载任务...</p>
        </div>
        <div v-else class="tasks-list">
          <div 
            class="task-item" 
            v-for="task in dailyTasks" 
            :key="task.id"
            :class="{ completed: task.completed }"
          >
            <div class="task-icon">{{ task.icon }}</div>
            <div class="task-info">
              <div class="task-name">{{ task.name }}</div>
              <el-progress 
                :percentage="task.progress" 
                :color="task.completed ? '#67c23a' : '#409eff'" 
              />
            </div>
            <div class="task-reward">
              <el-icon v-if="task.completed" class="check-icon" color="#67c23a"><Check /></el-icon>
              <template v-else>
                <span class="reward-icon">⭐</span>
                <span class="reward-value">+{{ task.reward }}</span>
              </template>
            </div>
          </div>
        </div>
      </section>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { usePetStore } from '@/stores/pet'
import { dashboardApi } from '@/api/dashboard'
import { ElMessage } from 'element-plus'
import { Check, ArrowRight } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const petStore = usePetStore()

const user = computed(() => userStore.user)
const pet = computed(() => petStore.pet)
const petLoading = ref(false)
const wordsLearned = ref(0)
const loading = ref(false)

// 每日任务数据
const dailyTasks = ref<any[]>([])

// 任务图标映射
const taskIcons: Record<string, string> = {
  login: '📅',
  learn_words: '📚',
  review: '📖',
  play_game: '🎮',
  feed_pet: '🍖'
}

// 十二生肖头像映射
const avatarEmojis = ['🐭', '🐮', '🐯', '🐰', '🐲', '🐍', '🐴', '🐏', '🐵', '🐔', '🐶', '🐷']

const getAvatarEmoji = (avatar?: string) => {
  if (!avatar) return '😊'
  const match = avatar.match(/\d+/)
  if (match) {
    const index = parseInt(match[0]) - 1
    return avatarEmojis[index] || '😊'
  }
  return '😊'
}

// 任务名称映射
const taskNames: Record<string, string> = {
  login: '每日签到',
  learn_words: '学习单词',
  review: '复习单词',
  play_game: '完成游戏',
  feed_pet: '喂养宠物'
}

// 加载Dashboard数据
const loadDashboardData = async () => {
  try {
    loading.value = true
    const res = await dashboardApi.getDashboardData()
    if (res.success && res.data) {
      // 更新每日任务
      dailyTasks.value = res.data.daily_tasks.map(task => ({
        id: task.id,
        name: taskNames[task.task_type] || task.task_type,
        icon: taskIcons[task.task_type] || '📋',
        progress: task.progress,
        completed: task.completed,
        reward: task.stars_reward,
        type: task.task_type
      }))
      
      // 更新学习统计
      wordsLearned.value = res.data.stats.words_learned
      
      // 更新宠物信息
      if (res.data.pet) {
        petStore.setPet(res.data.pet)
      }
    }
  } catch (error) {
    console.error('加载Dashboard数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取宠物图标
const getPetIcon = (type: string) => {
  const icons: Record<string, string> = {
    dragon: '🐲',
    fox: '🦊',
    panda: '🐼',
    rabbit: '🐰',
    cat: '🐱',
    dog: '🐶',
    bear: '🐻',
    penguin: '🐧'
  }
  return icons[type] || '🐾'
}

// 获取健康值颜色
const getHealthColor = (health: number) => {
  if (health >= 80) return '#67c23a'
  if (health >= 50) return '#e6a23c'
  return '#f56c6c'
}

// 喂食宠物
const feedPet = async () => {
  petLoading.value = true
  const success = await petStore.feedPet('basic')
  petLoading.value = false
  if (success) {
    ElMessage.success('喂食成功！宠物很开心~')
  }
}

// 与宠物玩耍
const playWithPet = async () => {
  petLoading.value = true
  const success = await petStore.playWithPet()
  petLoading.value = false
  if (success) {
    ElMessage.success('宠物玩得很开心！')
  }
}

// 处理下拉菜单命令
const handleCommand = (command: string) => {
  if (command === 'logout') {
    userStore.logout()
    router.push('/login')
  } else if (command === 'profile') {
    router.push('/profile')
  }
}

onMounted(async () => {
  console.log('Dashboard加载中...')
  
  // 加载Dashboard数据
  await loadDashboardData()
  
  // 获取用户详细信息
  await userStore.getUserInfo()
  
  console.log('Dashboard加载完成')
})
</script>

<style scoped lang="scss">
.dashboard-container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  position: relative;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 30px;
  position: sticky;
  top: 0;
  z-index: 100;

  .logo {
    font-size: 1.5rem;
    font-weight: bold;
    color: #fff;
    margin: 0;
  }

  .user-stats {
    display: flex;
    gap: 20px;

    .stat-item {
      display: flex;
      align-items: center;
      gap: 5px;
      color: #fff;
      font-size: 1.2rem;

      .icon {
        font-size: 1.5rem;
      }

      .value {
        font-weight: bold;
      }
    }
  }

  .user-info {
    display: flex;
    align-items: center;
    gap: 10px;
    color: #fff;

    .avatar {
      font-size: 2rem;
    }

    .username {
      font-weight: 500;
    }
  }
}

.main-content {
  padding: 30px;
  max-width: 1400px;
  margin: 0 auto;
}

.section-title {
  color: #fff;
  font-size: 1.5rem;
  margin-bottom: 20px;
  font-weight: bold;
}

.pet-section {
  padding: 30px;
  margin-bottom: 30px;

  .pet-display {
    display: flex;
    gap: 30px;
    align-items: center;

    .pet-avatar {
      position: relative;

      .pet-icon {
        font-size: 8rem;
        display: block;
      }

      .pet-level {
        position: absolute;
        bottom: -10px;
        right: -10px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: #fff;
        padding: 5px 15px;
        border-radius: 20px;
        font-weight: bold;
      }
    }

    .pet-info {
      flex: 1;

      .pet-name {
        color: #fff;
        font-size: 2rem;
        margin-bottom: 20px;
      }

      .pet-stats {
        display: flex;
        flex-direction: column;
        gap: 15px;
        margin-bottom: 20px;

        .stat-bar {
          .label {
            color: #fff;
            display: block;
            margin-bottom: 5px;
            font-size: 1.1rem;
          }
        }
      }

      .pet-actions {
        display: flex;
        gap: 10px;
      }
    }
  }
}

.quick-start {
  margin-bottom: 30px;

  .start-button {
    padding: 30px 40px;
    display: flex;
    align-items: center;
    gap: 30px;
    transition: all 0.3s;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.3) 0%, rgba(118, 75, 162, 0.3) 100%);
    border: 2px solid rgba(255, 255, 255, 0.1);

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 15px 40px rgba(102, 126, 234, 0.4);
      border-color: rgba(255, 255, 255, 0.3);
    }

    .start-icon {
      font-size: 5rem;
    }

    .start-content {
      flex: 1;

      h3 {
        color: #fff;
        font-size: 2rem;
        margin: 0 0 10px 0;
        font-weight: bold;
      }

      p {
        color: rgba(255, 255, 255, 0.8);
        font-size: 1.1rem;
        margin: 0;
      }
    }

    .arrow {
      font-size: 3rem;
      color: rgba(255, 255, 255, 0.7);
      transition: transform 0.3s;
    }

    &:hover .arrow {
      transform: translateX(10px);
    }
  }
}

.menu-section {
  margin-bottom: 30px;

  .menu-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;

    .menu-item {
      padding: 30px;
      text-align: center;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-10px);
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
      }

      .menu-icon {
        font-size: 4rem;
        margin-bottom: 15px;
      }

      .menu-title {
        color: #fff;
        font-size: 1.3rem;
        font-weight: bold;
        margin-bottom: 10px;
      }

      .menu-desc {
        color: rgba(255, 255, 255, 0.7);
        font-size: 0.9rem;
      }
    }
  }
}

.tasks-section {
  padding: 30px;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .section-title {
      margin-bottom: 0;
    }
  }

  .empty-tasks {
    text-align: center;
    color: rgba(255, 255, 255, 0.7);
    padding: 40px;
  }

  .tasks-list {
    display: flex;
    flex-direction: column;
    gap: 15px;

    .task-item {
      display: flex;
      align-items: center;
      gap: 20px;
      padding: 15px;
      background: rgba(255, 255, 255, 0.05);
      border-radius: 10px;
      transition: all 0.3s;

      &.completed {
        opacity: 0.7;
        background: rgba(103, 194, 58, 0.1);
      }

      .task-icon {
        font-size: 2.5rem;
      }

      .task-info {
        flex: 1;

        .task-name {
          color: #fff;
          font-size: 1.1rem;
          margin-bottom: 10px;
        }
      }

      .task-reward {
        display: flex;
        align-items: center;
        gap: 5px;
        color: #ffd700;
        font-size: 1.2rem;
        font-weight: bold;
        
        .check-icon {
          font-size: 2rem;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 15px;
  }

  .pet-display {
    flex-direction: column !important;
  }

  .menu-grid {
    grid-template-columns: repeat(2, 1fr) !important;
  }
}
</style>

